package com.tanhua.dubbo.api;


import com.tanhua.domain.mongo.*;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.dubbo.api.mongo.MovementApi;
import com.tanhua.dubbo.utils.IdWorker;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.scheduling.annotation.Async;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@DubboService
public class MovementApiImpl implements MovementApi {


    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IdWorker idWorker;

    @Autowired
    private MovementFriendImpl movementFriendImpl;

    @Override
    public String saveMovements(Movement movement) {
//        1、保存movement_detail    1毫秒
        movement.setId(new ObjectId());
        movement.setPid(idWorker.nextId());
        movement.setCreated(new Date().getTime());
        mongoTemplate.save(movement);
//        2、保存movement_mine_USERID(相册集表)  1毫秒
        MovementMine movementMine = new MovementMine();
        movementMine.setId(new ObjectId());
        movementMine.setMovementId(movement.getId());
        movementMine.setCreated(new Date().getTime());
        mongoTemplate.save(movementMine,"movement_mine_"+movement.getUserId());

//        向MQ中插入数据   1毫秒

        movementFriendImpl.saveTimeLine(movement);
        return movement.getId().toString();
    }



    @Override
    public PageResult queryFriendMovements(Long userId, Integer page, Integer pagesize) {
//        1、查询 好友时间线表 movement_firend_USERID
        Query query = new Query();

        long count = mongoTemplate.count(query, MovementFriend.class, "movement_friend_" + userId);

        query.with(Sort.by(Sort.Direction.DESC,"created"));
        query.limit(pagesize).skip((page-1)*pagesize);
        List<MovementFriend> movementFriendList = mongoTemplate.find(query, MovementFriend.class, "movement_friend_" + userId);
//        2、再去查movement_detail
        List<Movement> list = new ArrayList<>();
        for (MovementFriend movementFriend : movementFriendList) {
            Movement movement = mongoTemplate.findById( movementFriend.getMovementId(),Movement.class);
            if(movement!=null){
                list.add(movement);
            }

        }
        return new PageResult(page,pagesize,(int)count,list);
    }

    @Override
    public PageResult queryRecommendMovements(Long userId, Integer page, Integer pagesize) {
        //        1、查询 推荐 recommend_movement
        Query query = new Query(Criteria.where("userId").is(userId));
        long count = mongoTemplate.count(query, RecommendMovement.class);

        query.with(Sort.by(Sort.Direction.DESC,"created"));
        query.limit(pagesize).skip((page-1)*pagesize);
        List<RecommendMovement> recommendMovementList = mongoTemplate.find(query, RecommendMovement.class);
//        2、再去查movement_detail
        List<Movement> list = new ArrayList<>();
        for (RecommendMovement recommendMovement : recommendMovementList) {
            Movement movement = mongoTemplate.findById( recommendMovement.getMovementId(),Movement.class);
            if(movement!=null){
                list.add(movement);
            }
        }
        return new PageResult(page,pagesize,(int)count,list);
    }

    @Override
    public PageResult queryMyselfMovements(Long userId, Integer page, Integer pagesize) {
        //        1、查询 自己的相册集表 movement_mine_USERID
        Query query = new Query();

        long count = mongoTemplate.count(query, MovementMine.class, "movement_mine_" + userId);

        query.with(Sort.by(Sort.Direction.DESC,"created"));
        query.limit(pagesize).skip((page-1)*pagesize);
        List<MovementMine> movementMineList = mongoTemplate.find(query, MovementMine.class, "movement_mine_" + userId);
//        2、再去查movement_detail
        List<Movement> list = new ArrayList<>();
        for (MovementMine movementMine : movementMineList) {
            Movement movement = mongoTemplate.findById( movementMine.getMovementId(),Movement.class);
            if(movement!=null){
                list.add(movement);
            }
        }
        return new PageResult(page,pagesize,(int)count,list);
    }

    @Override
    public Movement queryMovementsById(String movementId) {

        return mongoTemplate.findById(new ObjectId(movementId),Movement.class);
    }

    @Override
    public void updateStateById(int state, String movementId) {
//        update table set state=?? where id=??
        Query query = new Query(Criteria.where("id").is(new ObjectId(movementId)));
        Update update = new Update();
        update.set("state",state);
        mongoTemplate.updateFirst(query,update,Movement.class);

    }

    @Override
    public PageResult queryUserMovements(Integer page, Integer pagesize, Long userId, Integer state) {

        Query query = new Query();
        //        Criteria.where("userId").is(userId).and("state").is(state)
        Criteria criteria = new Criteria();

        if(userId!=null){
            criteria.and("userId").is(userId);
        }
        if(state!=null){
            criteria.and("state").is(state);
        }
        query.addCriteria(criteria);
        query.with(Sort.by(Sort.Direction.DESC,"created")); //最新发布的朋友圈排到上面
        query.limit(pagesize).skip( (page-1) *pagesize );
        List<Movement> list = mongoTemplate.find(query, Movement.class);
        long count = mongoTemplate.count(query,Movement.class);
        //        关联movement_detail表中的数据
        return new PageResult(page,pagesize,(int)count,list);

    }

    @Override
    public void findByMovementId(List<String> ids, Integer state) {
        for (String id : ids) {
            Query query = new Query(Criteria.where("id").is(new ObjectId(id)));
            Update update = new Update();
            update.set("state", 1);
            mongoTemplate.updateFirst(query, update, Movement.class);
        }
    }

    @Override
    public void findByMovementId2(List<String> ids, Integer state) {
        for (String id : ids) {
            Query query = new Query(Criteria.where("id").is(new ObjectId(id)));
            Update update = new Update();
            update.set("state", 2);
            mongoTemplate.updateFirst(query, update, Movement.class);
        }

    }


}